import apiService from '../../utils/api.js';

class UserSettings {
  constructor(onSave) {
    this.onSave = onSave;
    this.container = document.createElement('div');
    this.container.classList.add('user-settings');

    // 用户头像
    this.avatarInput = document.createElement('input');
    this.avatarInput.type = 'file';
    this.avatarInput.accept = 'image/*';
    this.avatarInput.style.display = 'none';

    this.avatarPreview = document.createElement('img');
    this.avatarPreview.src = 'assets/images/default-avatar.png';
    this.avatarPreview.classList.add('avatar-preview');
    this.avatarPreview.addEventListener('click', () => this.avatarInput.click());

    // 用户名
    this.nameInput = document.createElement('input');
    this.nameInput.type = 'text';
    this.nameInput.placeholder = '输入用户名';
    this.nameInput.classList.add('name-input');

    // 保存按钮
    this.saveButton = document.createElement('button');
    this.saveButton.textContent = '保存设置';
    this.saveButton.classList.add('save-button');
    this.saveButton.addEventListener('click', () => this.handleSave());

    // 事件监听
    this.avatarInput.addEventListener('change', (e) => this.handleAvatarChange(e));

    this.container.appendChild(this.avatarPreview);
    this.container.appendChild(this.nameInput);
    this.container.appendChild(this.saveButton);
    this.container.appendChild(this.avatarInput);
  }

  async handleAvatarChange(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.avatarPreview.src = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }

  async handleSave() {
    const userData = {
      name: this.nameInput.value,
      avatar: this.avatarPreview.src
    };
    await this.onSave(userData);
  }

  update(settings) {
    if (settings) {
      this.nameInput.value = settings.name || '';
      this.avatarPreview.src = settings.avatar || 'assets/images/default-avatar.png';
    }
  }

  render() {
    return this.container;
  }
}

export default UserSettings;